﻿using System;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

namespace SvnLogParser
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var repos = File.ReadAllText(args[0]).Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList();

            Console.WriteLine("Testing {0} repos", repos.Count());

            var reposWithProblem = repos.Except(repos.AsParallel().Where(IsValid)).ToList();
            if (reposWithProblem.Any())
            {
                foreach (var r in reposWithProblem)
                {
                    Console.Error.WriteLine("repo {0} is not available", r);
                }
                Console.Error.WriteLine("{0} are not available", reposWithProblem.Count);
            }
            else
            {
                Console.WriteLine("All repos have been tested successfully");
            }
        }

        private static bool IsValid(string repo)
        {
            try
            {
                Console.WriteLine("Test repo {0}", repo);

                Parse(new ProcessRunner().Start(new Command(ConfigurationManager.AppSettings["svnPath"], string.Format("info {0}/{1}", ConfigurationManager.AppSettings["urlSvn"], repo))).StandardOutput);

                return true;
            }
            catch (ArgumentException)
            {
                return false;
            }
        }

        public static SvnInfo Parse(string output)
        {
            const RegexOptions options = RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.Multiline;
            var regexPath = new Regex(@"^Path\:\s*(?<Path>.*)", options);
            var regexRevision = new Regex(@"^Revision\:\s*(?<Revision>.*)", options);
            var regexUrl = new Regex(@"^Repository\s*Root\:\s*(?<Url>.*)", options);

            return new SvnInfo(Extract(output, regexPath, "Path"), Extract(output, regexUrl, "Url"), Extract(output, regexRevision, "Revision"));
        }

        private static string Extract(string output, Regex regex, string groupname)
        {
            var result = regex.Match(output).Groups[groupname].Value.Trim();

            if (string.IsNullOrEmpty(result))
            {
                throw new ArgumentException();
            }
            return result;
        }
    }
}